home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / var / lib / python-support / python2.6 / cupshelpers / openprinting.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  12.0 KB  |  425 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import urllib
  5. import httplib
  6. import platform
  7. import threading
  8. import tempfile
  9. import traceback
  10. import os
  11. import sys
  12. from xml.etree.ElementTree import XML
  13. from  import Device
  14. __all__ = [
  15.     'OpenPrinting']
  16.  
  17. def _normalize_space(text):
  18.     result = text.strip()
  19.     result = result.replace('\n', ' ')
  20.     i = result.find('  ')
  21.     while i != -1:
  22.         result = result.replace('  ', ' ')
  23.         i = result.find('  ')
  24.     return result
  25.  
  26.  
  27. class _QueryThread(threading.Thread):
  28.     
  29.     def __init__(self, parent, parameters, callback, user_data = None):
  30.         threading.Thread.__init__(self)
  31.         self.parent = parent
  32.         self.parameters = parameters
  33.         self.callback = callback
  34.         self.user_data = user_data
  35.         self.setDaemon(True)
  36.  
  37.     
  38.     def run(self):
  39.         query_command = '/query.cgi'
  40.         headers = {
  41.             'Content-type': 'application/x-www-form-urlencoded',
  42.             'Accept': 'text/plain' }
  43.         params = '%s&uilanguage=%s&locale=%s' % (urllib.urlencode(self.parameters), self.parent.language[0], self.parent.language[0])
  44.         self.url = 'http://%s%s?%s' % (self.parent.base_url, query_command, params)
  45.         result = None
  46.         status = 1
  47.         
  48.         try:
  49.             conn = httplib.HTTPConnection(self.parent.base_url)
  50.             conn.request('POST', query_command, params, headers)
  51.             resp = conn.getresponse()
  52.             status = resp.status
  53.             if status == 200:
  54.                 result = resp.read()
  55.             
  56.             conn.close()
  57.         except:
  58.             result = sys.exc_info()
  59.  
  60.         if status == 200:
  61.             status = 0
  62.         
  63.         if self.callback != None:
  64.             self.callback(status, self.user_data, result)
  65.         
  66.  
  67.  
  68.  
  69. class OpenPrinting:
  70.     
  71.     def __init__(self, language = None):
  72.         '''
  73.         @param language: language, as given by the first element of
  74.         locale.setlocale().
  75.         @type language: string
  76.         '''
  77.         if language == None:
  78.             import locale
  79.             
  80.             try:
  81.                 language = locale.getlocale(locale.LC_MESSAGES)
  82.             except locale.Error:
  83.                 e = None
  84.                 language = 'C'
  85.             except:
  86.                 None<EXCEPTION MATCH>locale.Error
  87.             
  88.  
  89.         None<EXCEPTION MATCH>locale.Error
  90.         self.language = language
  91.         self.base_url = 'www.openprinting.org'
  92.         self.onlyfree = 1
  93.         self.onlymanufacturer = 0
  94.  
  95.     
  96.     def cancelOperation(self, handle):
  97.         '''
  98.         Cancel an operation.
  99.  
  100.         @param handle: query/operation handle
  101.         '''
  102.         
  103.         try:
  104.             handle.callback = None
  105.         except:
  106.             pass
  107.  
  108.  
  109.     
  110.     def webQuery(self, parameters, callback, user_data = None):
  111.         '''
  112.         Run a web query for a driver.
  113.  
  114.         @type parameters: dict
  115.         @param parameters: URL parameters
  116.         @type callback: function
  117.         @param callback: callback function, taking (integer, user_data, string)
  118.         parameters with the first parameter being the status code, zero for
  119.         success
  120.         @return: query handle
  121.         '''
  122.         the_thread = _QueryThread(self, parameters, callback, user_data)
  123.         the_thread.start()
  124.         return the_thread
  125.  
  126.     
  127.     def searchPrinters(self, searchterm, callback, user_data = None):
  128.         '''
  129.         Search for printers using a search term.
  130.  
  131.         @type searchterm: string
  132.         @param searchterm: search term
  133.         @type callback: function
  134.         @param callback: callback function, taking (integer, user_data, string)
  135.         parameters with the first parameter being the status code, zero for
  136.         success
  137.         @return: query handle
  138.         '''
  139.         
  140.         def parse_result(status, data, result):
  141.             (callback, user_data) = data
  142.             if status != 0:
  143.                 callback(status, user_data, result)
  144.                 return None
  145.             status = 0
  146.             printers = { }
  147.             
  148.             try:
  149.                 root = XML(result)
  150.                 for printer in root.findall('printer'):
  151.                     id = printer.find('id')
  152.                     make = printer.find('make')
  153.                     model = printer.find('model')
  154.                     if id != None and make != None and model != None:
  155.                         idtxt = id.text
  156.                         maketxt = make.text
  157.                         modeltxt = model.text
  158.                         if idtxt and maketxt and modeltxt:
  159.                             printers[idtxt] = maketxt + ' ' + modeltxt
  160.                         
  161.                     modeltxt
  162.             except:
  163.                 status != 0
  164.                 status = 1
  165.                 printers = sys.exc_info()
  166.  
  167.             
  168.             try:
  169.                 callback(status, user_data, printers)
  170.             except:
  171.                 status != 0
  172.                 (type, value, tb) = sys.exc_info()
  173.                 tblast = traceback.extract_tb(tb, limit = None)
  174.                 if len(tblast):
  175.                     tblast = tblast[:len(tblast) - 1]
  176.                 
  177.                 extxt = traceback.format_exception_only(type, value)
  178.                 for line in traceback.format_tb(tb):
  179.                     print line.strip()
  180.                 
  181.                 print extxt[0].strip()
  182.  
  183.  
  184.         params = {
  185.             'type': 'printers',
  186.             'printer': searchterm,
  187.             'format': 'xml' }
  188.         return self.webQuery(params, parse_result, (callback, user_data))
  189.  
  190.     
  191.     def listDrivers(self, model, callback, user_data = None, extra_options = None):
  192.         '''
  193.         Obtain a list of printer drivers.
  194.  
  195.         @type model: string or cupshelpers.Device
  196.         @param model: foomatic printer model string or a cupshelpers.Device
  197.         object
  198.         @type callback: function
  199.         @param callback: callback function, taking (integer, user_data, string)
  200.         parameters with the first parameter being the status code, zero for
  201.         success
  202.         @type extra_options: string -> string dictionary
  203.         @param extra_options: Additional search options, see
  204.         http://www.linuxfoundation.org/en/OpenPrinting/Database/Query
  205.         @return: query handle
  206.         '''
  207.         
  208.         def parse_result(status, data, result):
  209.             (callback, user_data) = data
  210.             if status != 0:
  211.                 callback(status, user_data, result)
  212.             
  213.             
  214.             try:
  215.                 root = XML(result)
  216.                 drivers = { }
  217.                 for driver in root.findall('driver'):
  218.                     id = driver.attrib.get('id')
  219.                     if id == None:
  220.                         continue
  221.                     
  222.                     dict = { }
  223.                     for attribute in [
  224.                         'name',
  225.                         'url',
  226.                         'supplier',
  227.                         'license',
  228.                         'shortdescription']:
  229.                         element = driver.find(attribute)
  230.                         if element != None and element.text != None:
  231.                             dict[attribute] = _normalize_space(element.text)
  232.                             continue
  233.                     
  234.                     element = driver.find('licensetext')
  235.                     if element != None:
  236.                         dict['licensetext'] = element.text
  237.                     
  238.                     for boolean in [
  239.                         'nonfreesoftware',
  240.                         'recommended',
  241.                         'patents',
  242.                         'thirdpartysupplied',
  243.                         'manufacturersupplied']:
  244.                         dict[boolean] = driver.find(boolean) != None
  245.                     
  246.                     dict['freesoftware'] = not dict['nonfreesoftware']
  247.                     supportcontacts = []
  248.                     container = driver.find('supportcontacts')
  249.                     if container != None:
  250.                         for sc in container.findall('supportcontact'):
  251.                             supportcontact = { }
  252.                             if sc.text != None:
  253.                                 supportcontact['name'] = _normalize_space(sc.text)
  254.                             else:
  255.                                 supportcontact['name'] = ''
  256.                             supportcontact['url'] = sc.attrib.get('url')
  257.                             supportcontact['level'] = sc.attrib.get('level')
  258.                             supportcontacts.append(supportcontact)
  259.                         
  260.                     
  261.                     if supportcontacts:
  262.                         dict['supportcontacts'] = supportcontacts
  263.                     
  264.                     if not dict.has_key('name') or not dict.has_key('url'):
  265.                         continue
  266.                     
  267.                     container = driver.find('functionality')
  268.                     if container != None:
  269.                         functionality = { }
  270.                         for attribute in [
  271.                             'text',
  272.                             'lineart',
  273.                             'graphics',
  274.                             'photo',
  275.                             'speed']:
  276.                             element = container.find(attribute)
  277.                             if element != None:
  278.                                 functionality[attribute] = element.text
  279.                                 continue
  280.                         
  281.                         if functionality:
  282.                             dict[container.tag] = functionality
  283.                         
  284.                     
  285.                     packages = { }
  286.                     container = driver.find('packages')
  287.                     if container != None:
  288.                         for arch in container.getchildren():
  289.                             rpms = { }
  290.                             for package in arch.findall('package'):
  291.                                 rpm = { }
  292.                                 for attribute in [
  293.                                     'realversion',
  294.                                     'version',
  295.                                     'release',
  296.                                     'url',
  297.                                     'pkgsys']:
  298.                                     element = package.find(attribute)
  299.                                     if element != None:
  300.                                         rpm[attribute] = element.text
  301.                                         continue
  302.                                 
  303.                                 repositories = package.find('repositories')
  304.                                 if repositories != None:
  305.                                     for pkgsys in repositories.getchildren():
  306.                                         rpm.setdefault('repositories', { })[pkgsys.tag] = pkgsys.text
  307.                                     
  308.                                 
  309.                                 rpms[package.attrib['file']] = rpm
  310.                             
  311.                             packages[arch.tag] = rpms
  312.                         
  313.                     
  314.                     if packages:
  315.                         dict['packages'] = packages
  316.                     
  317.                     ppds = []
  318.                     container = driver.find('ppds')
  319.                     if container != None:
  320.                         for each in container.getchildren():
  321.                             ppds.append(each.text)
  322.                         
  323.                     
  324.                     if ppds:
  325.                         dict['ppds'] = ppds
  326.                     
  327.                     drivers[id] = dict
  328.                 
  329.                 callback(0, user_data, drivers)
  330.             except:
  331.                 callback(1, user_data, sys.exc_info())
  332.  
  333.  
  334.         if isinstance(model, Device):
  335.             model = model.id
  336.         
  337.         params = {
  338.             'type': 'drivers',
  339.             'moreinfo': '1',
  340.             'showprinterid': '1',
  341.             'onlynewestdriverpackages': '1',
  342.             'architectures': platform.machine(),
  343.             'noobsoletes': '1',
  344.             'onlyfree': str(self.onlyfree),
  345.             'onlymanufacturer': str(self.onlymanufacturer),
  346.             'printer': model,
  347.             'format': 'xml' }
  348.         if extra_options:
  349.             params.update(extra_options)
  350.         
  351.         return self.webQuery(params, parse_result, (callback, user_data))
  352.  
  353.  
  354.  
  355. def _simple_gui():
  356.     import gtk
  357.     import pprint
  358.     gtk.gdk.threads_init()
  359.     
  360.     class QueryApp('QueryApp', ()):
  361.         
  362.         def __init__(self):
  363.             self.openprinting = OpenPrinting()
  364.             self.main = gtk.Dialog('OpenPrinting query application', None, gtk.DIALOG_MODAL | gtk.DIALOG_NO_SEPARATOR, (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE, 'Search', 10, 'List', 20))
  365.             self.main.set_border_width(6)
  366.             self.main.vbox.set_spacing(2)
  367.             vbox = gtk.VBox(False, 6)
  368.             self.main.vbox.pack_start(vbox, True, True, 0)
  369.             vbox.set_border_width(6)
  370.             self.entry = gtk.Entry()
  371.             vbox.pack_start(self.entry, False, False, 6)
  372.             sw = gtk.ScrolledWindow()
  373.             self.tv = gtk.TextView()
  374.             sw.add(self.tv)
  375.             vbox.pack_start(sw, True, True, 6)
  376.             self.main.connect('response', self.response)
  377.             self.main.show_all()
  378.  
  379.         
  380.         def response(self, dialog, response):
  381.             if response == gtk.RESPONSE_CLOSE or response == gtk.RESPONSE_DELETE_EVENT:
  382.                 gtk.main_quit()
  383.             
  384.             if response == 10:
  385.                 self.openprinting.searchPrinters(self.entry.get_text(), self.search_printers_callback)
  386.             
  387.             if response == 20:
  388.                 self.openprinting.listDrivers(self.entry.get_text(), self.list_drivers_callback)
  389.             
  390.  
  391.         
  392.         def search_printers_callback(self, status, user_data, printers):
  393.             if status != 0:
  394.                 raise printers[1]
  395.             status != 0
  396.             text = ''
  397.             for printer in printers.values():
  398.                 text += printer + '\n'
  399.             
  400.             gtk.gdk.threads_enter()
  401.             self.tv.get_buffer().set_text(text)
  402.             gtk.gdk.threads_leave()
  403.  
  404.         
  405.         def list_drivers_callback(self, status, user_data, drivers):
  406.             if status != 0:
  407.                 raise drivers[1]
  408.             status != 0
  409.             text = pprint.pformat(drivers)
  410.             gtk.gdk.threads_enter()
  411.             self.tv.get_buffer().set_text(text)
  412.             gtk.gdk.threads_leave()
  413.  
  414.         
  415.         def query_callback(self, status, user_data, result):
  416.             gtk.gdk.threads_enter()
  417.             self.tv.get_buffer().set_text(str(result))
  418.             file('result.xml', 'w').write(str(result))
  419.             gtk.gdk.threads_leave()
  420.  
  421.  
  422.     q = QueryApp()
  423.     gtk.main()
  424.  
  425.